/*
 * Copyright (C) 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package adapters;

import org2.jogo.models.Leaderboard;
import org2.jogo.models.Pergunta;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public abstract class JogoOrgDbAdapter {

	private static final String	DATABASE_NAME		= "jogo_org2";
	private static final int	DATABASE_VERSION	= 1;
	private static final String	TAG					= "JogoOrgDbAdapter";

	protected DatabaseHelper	mDbHelper;
	protected SQLiteDatabase	mDb;
	protected Context			mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(Leaderboard.getTableCreationSQL());
			db.execSQL(Pergunta.getTableCreationSQL());
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
					+ ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + Leaderboard.getTableName());
			db.execSQL("DROP TABLE IF EXISTS " + Pergunta.getTableName());
			onCreate(db);
		}
	}

	/**
	 * Open the notes database. If it cannot be opened, try to create a new instance of the database. If it cannot be
	 * created, throw an exception to signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an initialization call)
	 * @throws SQLException if the database could be neither opened or created
	 */
	protected JogoOrgDbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	public SQLiteDatabase getDb() {
		if (!mDb.isOpen()) {
			throw new RuntimeException("A base de dados não está aberta.");
		}
		return this.mDb;
	}
}
